<?php

mysql_select_db("beca", mysql_connect("localhost", "root", ""));

$strConsulta  = "";
$strConsulta .= "SELECT ";
$strConsulta .= "  id_modelo, ";
$strConsulta .= "  B.nombre AS marca, ";
$strConsulta .= "  A.tipo, ";
$strConsulta .= "  A.version, ";
$strConsulta .= "  A.modelo, ";

$arrMarcasD = array();
$arrMarcasD["AA"] = array();

//$strConsulta = "SELECT * from cat_marcas_qualitas ORDER BY nombre ASC";
$strConsulta = "SELECT DISTINCT(marca) AS nombre FROM cat_modelos_ana";
$rs = mysql_query($strConsulta);
while($arrInfo = mysql_fetch_assoc($rs)) {
  $arrMarcasD[$arrInfo["nombre"]]["Q"] = $arrInfo["nombre"];
}

//$strConsulta = "SELECT DISTINCT(B.nombre), COUNT(*) AS tot FROM cat_modelos_sisa AS A JOIN cat_marcas AS B ON A.id_marca = B.id_marca WHERE A.anio >= 1984 GROUP BY B.id_marca ORDER BY B.nombre";
$strConsulta = "SELECT DISTINCT(B.nombre), COUNT(*) AS tot FROM cat_modelos_sisa AS A JOIN cat_marcas AS B ON A.id_marca = B.id_marca WHERE A.anio >= 1984 GROUP BY B.id_marca ORDER BY tot";
$rs = mysql_query($strConsulta);
while($arrInfo = mysql_fetch_assoc($rs)) {
  $arrMarcasD[$arrInfo["nombre"]]["A"] = $arrInfo["tot"];
}

// Hacer a prueba de quitar los solitos
foreach($arrMarcasD as $strNom => $arrInfoNom) {
  if($strNom == "AA") continue;
  if(count($arrInfoNom) < 2) {
    // Poner los Q en una tabla, y los A en otra
    if(isset($arrInfoNom["A"])) {
      $arrExA[$strNom] = $arrInfoNom["A"];
    } else {
      $arrExQ[$strNom] = $arrInfoNom["Q"];
    }
    
    unset($arrMarcasD[$strNom]);
  }
}

// Ahora buscar las marcas que YA existen dadas de alta, para no mostrarlas en los faltantes
$strConsulta = "SELECT * FROM cat_marcas_ana_aig";
$rs = mysql_query($strConsulta);
while($arrInfo = mysql_fetch_assoc($rs)) {
  if(isset($arrExA[$arrInfo["marca_aig"]])) {
    unset($arrExA[$arrInfo["marca_aig"]]);
    $arrMarcasD["AA"][$arrInfo["marca_ana"]][] = $arrInfo["marca_aig"];
  }
  if(isset($arrExQ[$arrInfo["marca_ana"]])) {
    unset($arrExQ[$arrInfo["marca_ana"]]);
  }
}

echo "<pre>";

foreach($arrMarcasD as $strN => $strD) {
//  echo "INSERT INTO cat_marcas_ana_aig (marca_ana, marca_aig) VALUES ('$strN', '$strN');\n";
}

print_r($arrExA);
print_r($arrExQ);
print_r($arrMarcasD);

?>
